﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PessModel;
using System.Data;
using System.Web.Security;
using PessMvc.Models;

namespace PessMvc.Controllers
{
    [Authorize]
    public class ScoreController : Controller
    {
        //
        // GET: /Score/
        private PESSEntities db;

        public ScoreController()
        {
            db = new PESSEntities();
        }

        public ActionResult ArchiveExpertScores(int archiveID)
        {
            //Get Current User Name
            MembershipUser user=Membership.GetUser();
            if (Roles.IsUserInRole(user.UserName,"ExpertJudge"))
            {
                string expertSerialNumber = user.UserName;//"A1S7PW1";Membership

                var scores = db.sp_GetArchiveExpertScores(expertSerialNumber, archiveID).ToList();
                return View(scores);
            }
            else
            {
                return View();
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(int ruleID, int archiveID)
        {
            //Get Current User Name
            string expertSerialNumber = Membership.GetUser().UserName;

            var score = (from s in db.Scores
                         where s.ArchiveID == archiveID && s.RuleID == ruleID && s.ExpertJudgeSerialNumber == expertSerialNumber
                         select s).SingleOrDefault();

            return View(score);
        }

        [HttpPost]
        public ActionResult Edit(Score score)
        {
            //Get Current User Name
            string expertSerialNumber = Membership.GetUser().UserName;//"A1S7PW1";
            score.ExpertJudgeSerialNumber = expertSerialNumber;

            if (ModelState.IsValid)
            {
                if (ScoreValueIsLessthanLimit(score))
                {
                    var pessScore = db.Scores.Find(score.RuleID, score.ArchiveID, expertSerialNumber);
                    if (pessScore == null)
                    {
                        db.Scores.Add(score);
                    }
                    else
                    {
                        pessScore.Value = score.Value;
                        db.Entry(pessScore).State = EntityState.Modified;
                        //db.ObjectStateManager                    
                    }
                    db.SaveChanges();
                    return RedirectToAction("Details", "Archive", new { id = score.ArchiveID });
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "输入的分数高于规则限值！");
                }
            }
            return View(score);
        }

        private bool ScoreValueIsLessthanLimit(Score score)
        {
            bool isLessThan = false;
            PessModel.Rule rule = db.Rules.Find(score.RuleID);
            if (score.Value <= rule.Value&&score.Value>=0)
            {
                isLessThan= true;
            }
            return isLessThan;
        }

        public ActionResult EditScores(int archiveID)
        {
            MembershipUser user = Membership.GetUser();
            if (Roles.IsUserInRole(user.UserName, "ExpertJudge"))
            {
                string expertSerialNumber = user.UserName;//"A1S7PW1";Membership

                var scores = db.sp_GetArchiveExpertScores(expertSerialNumber, archiveID);
                return View(scores);
            }
            else
            {
                return View();
            }
        }

        public ActionResult EditScores2(int archiveID)
        {
            ViewBag.ArchiveID = archiveID;
            ViewBag.SerialNumber = db.Archives.Find(archiveID).SerialNumber;
            return EditScores(archiveID);
        }
        [HttpPost]
        public ActionResult SaveScores2(List<Score> scores)
        {
            
            //Get Current User Name
            string expertSerialNumber = Membership.GetUser().UserName;//"A1S7PW1";
            int archiveID=SaveScoresBL(scores, expertSerialNumber);
            return RedirectToAction("Details", "Archive", new { id = archiveID });
        }

        private int SaveScoresBL(List<Score> scores, string expertSerialNumber)
        {
            if (ModelState.IsValid)
            {
                foreach (var score in scores)
                {
                    score.ExpertJudgeSerialNumber = expertSerialNumber;

                    if (ScoreValueIsLessthanLimit(score))
                    {
                        var pessScore = db.Scores.Find(score.RuleID, score.ArchiveID, expertSerialNumber);
                        if (pessScore == null)
                        {
                            db.Scores.Add(score);
                        }
                        else
                        {
                            pessScore.Value = score.Value;
                            db.Entry(pessScore).State = EntityState.Modified;
                            //db.ObjectStateManager                    
                        }
                        db.SaveChanges();
                        //
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "输入的分数高于规则限值！");
                    }
                }
            }
            return scores.First().ArchiveID;
            
        }

        [HttpPost]
        public ActionResult DeleteScores2(int archiveID)
        {
            DeleteScores(archiveID);
            return RedirectToAction("Details", "Archive", new { id = archiveID });
        }

        [HttpPost]
        public string DeleteScores(int archiveID)
        {
            MembershipUser user = Membership.GetUser();
            if (Roles.IsUserInRole(user.UserName, "ExpertJudge"))
            {
                string expertSerialNumber = user.UserName;//"A1S7PW1";Membership
                var scores = db.Scores.Where(s => s.ArchiveID == archiveID && s.ExpertJudgeSerialNumber == expertSerialNumber).ToList();
                foreach (var s in scores)
                {
                    db.Scores.Remove(s);
                }
                db.SaveChanges();
            }
            return "ok";
        }

        [Authorize(Roles="Admin")]
        public ActionResult ExpertScores(int archiveID)
        {
            ExpertScoresModel model = new ExpertScoresModel();
 
            var archive = db.Archives.Find(archiveID);
            //model.ExpertScores=archive.Scores.Select(s => s.ExpertJudge).Distinct();
            model.ExpertScores=(from s in db.Scores                                
                               where s.ArchiveID==archiveID
                               group s by s.ExpertJudgeSerialNumber into scores
                               select new ExpertScore{
                                   RealName=scores.FirstOrDefault().ExpertJudge.RealName,  
                                   ExpertSN=scores.Key, 
                                   TotalScore=(decimal)scores.Sum(x=>x.Value) 
                               }).ToList();
            model.ArchiveSN = archive.SerialNumber;
            model.ArchiveID = archive.ID;
            model.ProjectTitle = archive.ProjectTitle;
            model.AuthorName = archive.TeacherName;
            return View(model);
        }
        [Authorize(Roles = "Admin")]
        public ActionResult InputExpertScore(int archiveID)
        {
            var archive=db.Archives.Find(archiveID);
            if (archive != null)
            {
                InputExpertScoreModel model = new InputExpertScoreModel();
                model.ArchiveID = archiveID;
                model.ArchiveSN = archive.SerialNumber;
                model.ExpertJudges  = db.ExpertJudges.Where(e => e.ExpertGroup.SubjectID == archive.SubjectID).ToList();
                model.Scores = db.sp_GetArchiveExpertScores("", archiveID).ToList();
                return View(model);
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult InputExpertScore(List<Score> scores, string expertSN)
        {
            int archiveID=SaveScoresBL(scores, expertSN);
            return RedirectToAction("ExpertScores", "Score", new { archiveID = archiveID });
        }
        public ActionResult EditExpertScores(string expertSN, int archiveID)
        {
            var archive = db.Archives.Find(archiveID);
            if (archive != null)
            {
                InputExpertScoreModel model = new InputExpertScoreModel();
                model.ArchiveID = archiveID;
                model.ArchiveSN = archive.SerialNumber;
                model.ExpertJudges = db.ExpertJudges.Where(e => e.SerialNumber == expertSN).ToList();
                model.Scores = db.sp_GetArchiveExpertScores(expertSN, archiveID).ToList();
                return View(model);
            }
            else
            {
                return View();
            }
        }
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public ActionResult DeleteExpertScores(string expertSN, int archiveID)
        {
            string expertSerialNumber = expertSN;
            var scores = db.Scores.Where(s => s.ArchiveID == archiveID && s.ExpertJudgeSerialNumber == expertSerialNumber).ToList();
            foreach (var s in scores)
            {
                db.Scores.Remove(s);
            }
            db.SaveChanges();
            
            return RedirectToAction("ExpertScores", "Score", new { archiveID = archiveID });
        }
    }
}
